<?php
declare (strict_types = 1);

namespace app\api\controller\ucenter;

use app\api\controller\Api;
use app\common\service\WechatService;
use app\common\system\logic\UserLogic;
use app\common\system\logic\UserRoleLogic;
use ding\Ding;
use think\db\exception\DbException;
use think\Exception;

class Grant extends Api
{
    public function getRole()
    {
        $post = $this->request->post();
        if (empty($post['user_id'])) return error([], '参数错误');

        $logic = new UserRoleLogic();
        $result['roles'] = $logic->getUserRole($post['user_id']);

        return success($result, '获取数据成功');
    }

    // 授权角色
    public function bindRole()
    {
        $post = $this->request->post();

        // 验证用户是否存在
        $userLogic = new \app\common\system\logic\UserLogic();
        $target = $userLogic->getUser($post['user_id']);
        if (!$target['id']) return error([], '用户不存在');

        $user = $this->request->user;
        $userRoleLogic = new \app\common\system\logic\UserRoleLogic();
        $rs = $userRoleLogic->updateUserRole($post['user_id'], $post['role'], $user['id']);

        if ($rs) {
            return success([], '绑定权限成功');
        } else {
            return error([], '绑定权限失败');
        }
    }

    // 根据手机号同步钉钉ID
    public function bindDing()
    {
        $user = $this->request->user;
        $model = new \app\common\system\model\User();
        $row = $model->where('id', $user['id'])->find();

        if (empty($row->mobile)) {
            return error([], "未设置手机号");
        }

        $ding = new Ding();
        try {
            $dingId = $ding->getUserIdByMobile($row->mobile);
        } catch (Exception $e) {
            return error([], $e->getMessage(), $e->getCode());
        }

        try {
            $row->save(['dingding' => $dingId]);
            $userLogic = new UserLogic();
            $userLogic->resetUserCache($user['id']);
            return success([], "同步成功");
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }
    }

    public function syncOpenid() {
        $post = $this->request->post();
        $user = $this->request->user;
        $model = new \app\common\system\model\User();
        $row = $model->where("id", $user['id'])->find();
        // 若果已经绑定过了，就不再绑定
        if (!empty($row->openid)) {
            return error(['openid' => $row->openid], '已经绑定过openid');
        }

        $wechat = new WechatService();

        $arr = $wechat->getUserIdByCode($post['code']);

        if (!empty($arr['openid'])) {
            $row->save(['openid' => $arr['openid']]);
            return success($arr,"获取openid成功");
        } else {
            return error($arr, '获取openid失败');
        }

    }
}
